package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func main() {
	//resp, err := http.Get("https://www.baidu.com/")
	//if err != nil {
	//	fmt.Printf("get failed, err:%v\n", err)
	//	return
	//}
	//defer resp.Body.Close() //程序在使用完response后必须关闭回复的主体。
	//body, err := ioutil.ReadAll(resp.Body)
	//if err != nil {
	//	fmt.Printf("read from resp.Body failed, err:%v\n", err)
	//	return
	//}
	//fmt.Print(string(body))

	//GetwithParam()

	PostDemo()

}

//带参数的get请求示例
func GetwithParam() {
	apiUrl := "http://127.0.0.1:8080/demo1"
	data := url.Values{}
	data.Set("name", "ybl")
	u, err := url.ParseRequestURI(apiUrl)
	if err != nil {
		return
	}

	u.RawQuery = data.Encode() //url encode ,这里会在url中读取到
	resp, err := http.Get(u.String())
	if err != nil {
		fmt.Printf("post failed, err:%v\n", err)
		return
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get resp failed, err:%v\n", err)
		return
	}
	fmt.Println(string(b))
}

//Post的请求示例
func PostDemo() {
	url := "http://127.0.0.1:8080/demo2"
	contentType := "application/json"
	data := `{"name":"小王子","age":18}`
	resp, err := http.Post(url, contentType, strings.NewReader(data))
	if err != nil {
		fmt.Printf("post failed, err:%v\n", err)
		return
	}
	defer resp.Body.Close()
	b, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(b))
}
